package com.xxxcompnay.shop.servlet;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class Listener1 implements ServletContextListener,HttpSessionAttributeListener,HttpSessionListener
{

	@Override
	public void contextInitialized(ServletContextEvent sce) 
	{
		System.out.println("ServletContext 初始化了");
		
		List<String> names = new ArrayList<>();
		names.add("admin");
		ServletContext context = sce.getServletContext();
		context.setAttribute("names", names);
	}
	
	
	public void attributeAdded(HttpSessionBindingEvent event)
	{
		// 会话对向
		HttpSession session = event.getSession();
		// 得到放入的值
		String name = (String)event.getValue();
		
		// 放入在线用户列表
		ServletContext context = event.getSession().getServletContext();
		List<String> names = (List<String>)context.getAttribute("names");
		names.add(name);
		context.setAttribute("names", names);
	}
	
	@Override
	public void sessionDestroyed(HttpSessionEvent se) 
	{
		System.out.println("会话 销毁了");
		// 会话对向
		HttpSession session = se.getSession();
		// 得到放入的值
		String name = (String)session.getAttribute("username");
		System.out.println(name);
		
		// 放入在线用户列表
		ServletContext context = se.getSession().getServletContext();
		List<String> names = (List<String>)context.getAttribute("names");
		names.remove(name);
		context.setAttribute("names", names);
	}
	
}